/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GoLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_01_01			*/
/*	File:		GoMysql.go			*/
/********************************************************/

package GoSql

import (
	. "GoGlb"
	"database/sql"
)

type GoMysql struct {
	db	*sql.DB
}

func (s *GoMysql) GoMysqlClose() {
	s.db.Close()
}

func (s *GoMysql) GoMysqlOpen(n string) error {
	var err error
	s.db, err = sql.Open("mysql", n)
	return err
}

func (s *GoMysql) GoMysqlDisplay(m []map[string] string) {
	for i, n := range m {
		GoPrint("Record[%04d]: ", i + 1)
		for k, v := range n {
			GoPrint("%s[%s], ", k, v)
		}
		GoPrtln()
	}
}

func (s *GoMysql) GoMysqlInsert(q string) error {
	return s.__MysqQuery(q)
}

func (s *GoMysql) GoMysqlUpdate(q string) error {
	return s.__MysqQuery(q)
}

func (s *GoMysql) GoMysqlDelete(q string) error {
	return s.__MysqQuery(q)
}

func (s *GoMysql) GoMysqlSelect(q string) []map[string] string {
	r := []map[string] string{}
	if row, err := s.db.Query(q); nil == err {
		col, _ := row.Columns()
		key := make([]interface{}, len(col))
		val := make([]interface{}, len(col))

		for i := range val {
			key[i] = &val[i]
		}
		for row.Next() {
			if nil == row.Scan(key...) {
				m := make(map[string] string)
				for k, v := range val {
					m[col[k]] = string(v.([]byte))
				}
				r = append(r, m)
			}
		}
	}
	return r
}

func (s *GoMysql) GoMysqlPreIns(q string, v ...interface{}) int64 {
	var ret int64
	if res, err := s.__MysqlPrepare(q, v...); nil == err {
		ret, err = res.LastInsertId()
	}
	return ret
}

func (s *GoMysql) GoMysqlPreUpd(q string, v ...interface{}) int64 {
	return s.__MysqlAffect(q, v...)
}

func (s *GoMysql) GoMysqlPreDel(q string, v ...interface{}) int64 {
	return s.__MysqlAffect(q, v...)
}

func (s *GoMysql) __MysqQuery(q string) error {
	_, e := s.db.Query(q)
	return e
}

func (s *GoMysql) __MysqlAffect(q string, v ...interface{}) int64 {
	var ret int64
	if res, err := s.__MysqlPrepare(q, v...); nil == err {
		ret, err = res.RowsAffected()
	}
	return ret
}

func (s *GoMysql) __MysqlPrepare(q string, v ...interface{}) (sql.Result, error) {
	var err error
	var stm *sql.Stmt
	var res sql.Result
	if stm, err = s.db.Prepare(q); nil == err {
		res, err = stm.Exec(v...)
	}
	return res, err
}
